package com.example.myplayer

import android.view.View
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

//视频的播放状态
enum class PlayStatus {
    Playing, Paused, Completed, NoReady
}

class PlayViewModel : ViewModel() {

    //视频控制条出现时间
    private var controllerShowTime = 0L

    //获得MediaPlayer()实例,MyMediaPlayer()自定义的
    //val mediaPlayer = MediaPlayer()
    val mediaPlayer = MyMediaPlayer()

    //视频的播放状态
    private val _playStatus = MutableLiveData(PlayStatus.NoReady)
    val playStatus: LiveData<PlayStatus> = _playStatus

    //视频缓冲百分比
    private val _bufferPercent = MutableLiveData(0)
    val bufferPercent: LiveData<Int> = _bufferPercent

    //视频控制条初始不可见
    private val _controllerFrameVisibility = MutableLiveData(View.INVISIBLE)
    val controllerFrameVisibility: LiveData<Int> = _controllerFrameVisibility

    //视频缓冲完成前的显示转动进度条可见
    private val _progerssBarVisibility = MutableLiveData(View.VISIBLE)
    val progerssBarVisibility: LiveData<Int> = _progerssBarVisibility

    //视频分辨率
    private val _videowResolution = MutableLiveData(Pair(0, 0))
    val videowResolution: LiveData<Pair<Int, Int>> = _videowResolution

    //初始化
    init {
        loadVideo()

    }


    /**
     * apply函数扩展了所有的泛型对象,在闭包范围内可以任意调用该对象的任意方法,并在最后返回该对象.
    主要的作用：是可以用来简化初始化对象的功能。
    特别需要注意的是apply函数中表示对象本身使用的是this关键字而不是it。
     */
    //播放视频
    private fun loadVideo() {
        mediaPlayer.apply {
            //视频缓冲完成前的转动进度条可见
            _progerssBarVisibility.value = View.VISIBLE

            //初始化视频的播放状态为未准备好
            _playStatus.value = PlayStatus.NoReady
            //视频源的地址
            setDataSource("https://stream7.iqilu.com/10339/upload_transcode/202002/09/20200209105011F0zPoYzHry.mp4")
            //视频加载完成前需要完成的事情（监听器）
            setOnPreparedListener {
                //视频缓冲完成时，转动进度条消失
                _progerssBarVisibility.value = View.INVISIBLE
                // 循环播放
                //isLooping = true
                //开始播放
                it.start()
                //视频的播放状态为播放
                _playStatus.value = PlayStatus.Playing
            }

            //视频分辨率切换的监听器
            setOnVideoSizeChangedListener { _, width, height ->
                _videowResolution.value = Pair(width, height)
            }

            //视频缓冲百分比监听
            setOnBufferingUpdateListener { _, percent ->
                _bufferPercent.value = percent
            }

            //视频播放完的监听
            setOnCompletionListener {
                //视频的播放状态
                _playStatus.value = PlayStatus.Completed
            }

            //拖动完成的监听，拖动完成后隐藏视频控制条
            setOnSeekCompleteListener {
                mediaPlayer.start()
                _progerssBarVisibility.value = View.INVISIBLE

            }
            //准备视频播放
            prepareAsync()
        }
    }

    //改变播放状态
    fun togglePlayerStatus() {
        when (_playStatus.value) {

            PlayStatus.Playing -> {
                mediaPlayer.pause()
                _playStatus.value = PlayStatus.Paused
            }

            PlayStatus.Paused -> {
                mediaPlayer.start()
                _playStatus.value = PlayStatus.Playing
            }

            PlayStatus.Completed -> {
                mediaPlayer.start()
                _playStatus.value = PlayStatus.Playing
            }
            else -> return
        }

    }


    //点击视频会出现控制条
    fun toggleControllerVisibility() {
        if (_controllerFrameVisibility.value == View.INVISIBLE) {
            _controllerFrameVisibility.value = View.VISIBLE

            controllerShowTime = System.currentTimeMillis()
            //点击3秒后隐藏控制条(避免3秒内重复点击视频）
            viewModelScope.launch {
                delay(3000)
                if (System.currentTimeMillis() - controllerShowTime > 3000) {
                    _controllerFrameVisibility.value = View.INVISIBLE
                }
            }
        } else {
            _controllerFrameVisibility.value = View.INVISIBLE
        }
    }


    //重新发送宽高比信息
    fun emitVideoResolution() {
        _videowResolution.value = _videowResolution.value
    }

    //拖动视频播放进度条
    fun playSeekToProgress(progress: Int) {
        //拖动视频播放进度条前显示控制条
        _progerssBarVisibility.value = View.VISIBLE
        mediaPlayer.seekTo(progress)
    }

    override fun onCleared() {
        super.onCleared()
        //释放资源
        mediaPlayer.release()
    }

}